<template>
  <div class="tree-select-wrapper">
    <el-popover
      ref="popover"
      placement="bottom-start"
      width="300"
      trigger="click"
      :disabled="disabled"
    >
      <div class="popover-content">
        <el-input
          v-model="filterText"
          placeholder="输入分类名称搜索"
          clearable
          prefix-icon="el-icon-search"
          class="search-input"
        />
        <el-tree
          ref="tree"
          :data="filteredTree"
          :props="treeProps"
          :filter-node-method="filterNode"
          :highlight-current="true"
          node-key="categoryId"
          :expand-on-click-node="false"
          :default-expand-all="expandAll"
          @node-click="handleNodeClick"
        >
          <span slot-scope="{ node }" class="tree-node">
            <i :class="node.icon || 'el-icon-folder'"></i>
            <span>{{ node.label }}</span>
          </span>
        </el-tree>
      </div>
      <el-input
        slot="reference"
        v-model="selectedLabel"
        :placeholder="placeholder"
        :clearable="clearable"
        :disabled="disabled"
        readonly
        @clear="handleClear"
      >
        <i slot="suffix" class="el-icon-arrow-down el-input__icon"></i>
      </el-input>
    </el-popover>
  </div>
</template>

<script>
import { listCategory } from "@/api/question/category";

export default {
  name: "InputAndSearchWithTree",
  props: {
    value: {
      type: [String, Number],
      default: ''
    },
    placeholder: {
      type: String,
      default: '请选择分类'
    },
    clearable: {
      type: Boolean,
      default: true
    },
    disabled: {
      type: Boolean,
      default: false
    },
    expandAll: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      filterText: '',
      treeProps: {
        label: 'categoryName',
        children: 'children'
      },
      categoryList: [],
      selectedLabel: ''
    };
  },
  computed: {
    filteredTree() {
      if (!this.filterText) return this.categoryList;
      return this.categoryList.filter(node =>
        this.filterNode(this.filterText, node)
      );
    }
  },
  watch: {
    value: {
      immediate: true,
      handler(newVal) {
        if (newVal) {
          this.$nextTick(() => {
            this.initSelectedLabel();
          });
        } else {
          this.selectedLabel = '';
        }
      }
    },
    filterText(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.loadCategories();
  },
  methods: {
    async loadCategories() {
      try {
        const res = await listCategory({pageSize: 1000});
        this.categoryList = this.handleTree(res.data, "categoryId");
        this.initSelectedLabel();
      } catch (error) {
        console.error('加载分类失败:', error);
        this.$message.error('分类数据加载失败');
      }
    },

    initSelectedLabel() {
      if (this.value && this.categoryList.length) {
        const node = this.findNode(this.categoryList, this.value);
        if (node) {
          this.selectedLabel = node.categoryName;
          this.$nextTick(() => {
            this.$refs.tree.setCurrentKey(this.value);
          });
        }
      }
    },

    findNode(nodes, id) {
      for (const node of nodes) {
        if (node.categoryId === id) return node;
        if (node.children) {
          const found = this.findNode(node.children, id);
          if (found) return found;
        }
      }
      return null;
    },

    filterNode(query, data) {
      return data.categoryName.includes(query);
    },

    handleNodeClick(data) {
      this.selectedLabel = data.categoryName;
      this.$emit('input', data.categoryId);
      this.$emit('change', data);
      this.$refs.popover.doClose();
    },

    handleClear() {
      this.selectedLabel = '';
      this.$emit('input', '');
      this.$emit('change', null);
    },

    handleTree(data, idKey = 'id') {
      const map = {};
      const tree = [];
      data.forEach(item => {
        map[item[idKey]] = {...item, children: []};
      });
      data.forEach(item => {
        const parent = map[item.parentId || 0];
        parent ? parent.children.push(map[item[idKey]]) : tree.push(map[item[idKey]]);
      });
      return tree;
    },

    // 新增方法：设置当前选中的分类
    setCurrentKey(id) {
      if (id && this.$refs.tree) {
        this.$nextTick(() => {
          this.$refs.tree.setCurrentKey(id);
          const node = this.findNode(this.categoryList, id);
          if (node) {
            this.selectedLabel = node.categoryName;
          }
        });
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.tree-select-wrapper {
  position: relative;

  .popover-content {
    padding: 10px;

    .search-input {
      margin-bottom: 10px;
    }
  }

  .el-tree {
    max-height: 300px;
    overflow: auto;

    &::v-deep .el-tree-node__content {
      height: 36px;
    }

    .tree-node {
      display: flex;
      align-items: center;

      i {
        margin-right: 8px;
        color: #f0a70a;
      }
    }
  }

  .el-icon-arrow-down {
    transition: transform 0.3s;

    &.is-reverse {
      transform: rotate(180deg);
    }
  }
}
</style>
